<template>
  <div class="message-container">
    <!-- 好友/联系人列表 -->
    <aside class="contacts">
      <h3>联系人</h3>
      <ul>
        <!-- 正常联系人 -->
        <li
          v-for="contact in contacts"
          :key="contact.id"
          @click="selectContact(contact)"
          :class="{ active: selectedContact?.id === contact.id }"
        >
          {{ contact.username }}
        </li>



        <!-- 粉丝 -->
        <h3>粉丝</h3>
        <li
          v-for="follower in followers"
          :key="follower.id"
          @click="selectContact(follower)"
          :class="{ active: selectedContact?.id === follower.id }"
        >
          {{ follower.username }}
        </li>

                <!-- 陌生人 -->
        <h3>陌生人</h3>
        <li
          v-for="stranger in strangers"
          :key="stranger.id"
          @click="selectContact(stranger)"
          :class="{ active: selectedContact?.id === stranger.id }"
        >
          {{ stranger.username }}
        </li>
      </ul>
    </aside>

    <!-- 聊天区域 -->
   <main class="chat-box">
  <div class="chat-header">
    <span v-if="selectedCategory === 'contacts' && selectedContact">
      当前聊天对象：{{ selectedContact.username }}
    </span>
    <span v-else>
      请选择聊天对象
    </span>
  </div>

  <div class="messages" ref="messagesContainer">
    <div
      v-for="msg in messages"
      :key="msg.id"
      :class="['message', { mine: msg.postUserId === currentUser.id }]"
    >
      <p>{{ msg.content }}</p>
      <small>{{ formatTime(msg.createTime) }}</small>
    </div>
  </div>

  <div class="input-area">
    <textarea
      v-model="newMessage"
      @keyup.enter="sendMessage"
      placeholder="输入消息..."
      class="message-input"
    />
    <button @click="sendMessage">发送</button>
  </div>
</main>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { UserInforStore } from '@/stores/userInforStore'
import { getContacts, getFollowers, getStrangers, getChatMessages, addMessage } from '@/api/messageApi'

const { userInfor } = UserInforStore()
import { useRoute } from 'vue-router'

const route = useRoute()
// 当前用户（应从登录状态获取）
const currentUser = {}

// 好友列表
const contacts = ref([])
const strangers = ref([])
const followers = ref([])

// 当前选中的联系人或分类
const selectedContact = ref(null)
const selectedCategory = ref('contacts') // contacts / stranger / follower

// 消息列表
const messages = ref([])

// 输入框内容
const newMessage = ref('')

// 消息容器用于自动滚动到底部
const messagesContainer = ref(null)

// 轮询间隔时间（毫秒）
const POLLING_INTERVAL = 1000 // 每5秒更新一次

// 定时器ID
let pollingIntervalId = null

// 格式化时间
const formatTime = (timeStr) => {
  const date = new Date(timeStr)
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

// 获取与指定好友的消息
const fetchMessagesWith = async (contactId) => {
  try {
    const res = await getChatMessages(currentUser.id, contactId)
    messages.value = res
    scrollToBottom()
  } catch (error) {
    console.error('获取消息失败:', error)
  }
}

// 发送消息
const sendMessage = async () => {
  const content = newMessage.value.trim()
  if (!content || !selectedCategory.value) return

  let payload = {
    content
  }

  if (selectedCategory.value === 'contacts' && selectedContact.value) {
    payload.receiveUserId = selectedContact.value.id
  } else if (selectedCategory.value === 'stranger') {
    payload.receiveUserId = 'stranger'
  } else if (selectedCategory.value === 'follower') {
    payload.receiveUserId = 'follower'
  }
  payload.postUserId = currentUser.id
  console.log(payload)
  await addMessage(payload)

  messages.value.push({
    id: Date.now().toString(),
    content,
    postUserId: currentUser.id,
    receiveUserId: payload.receiveUserId,
    createTime: new Date().toISOString()
  })

  newMessage.value = ''
  scrollToBottom()
}

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 点击切换联系人并加载消息
const selectContact = (contact) => {
  selectedContact.value = contact
  selectedCategory.value = 'contacts'
  fetchMessagesWith(contact.id)
}

// 获取好友列表
const fetchContacts = async () => {
  try {
    const getContact = await getContacts(currentUser.id)
    contacts.value = getContact
    const getFollower = await getFollowers(currentUser.id)
    followers.value = getFollower
    const Stranger = await getStrangers(currentUser.id)
    strangers.value = Stranger
  } catch (error) {
    console.error('获取好友列表失败:', error)
  }
}

// 开始轮询
const startPolling = () => {
  if (pollingIntervalId !== null) return // 避免重复启动

  pollingIntervalId = setInterval(async () => {
    if (selectedContact.value) {
      await fetchMessagesWith(selectedContact.value.id)
    }
  }, POLLING_INTERVAL)
}

// 停止轮询
const stopPolling = () => {
  if (pollingIntervalId !== null) {
    clearInterval(pollingIntervalId)
    pollingIntervalId = null
  }
}

onMounted(async() => {
  console.log(userInfor.id)
  currentUser.id = userInfor.id
  await fetchContacts()
  // 如果有 contactId 参数，则自动选中该联系人
  if (route.query.contactId) {
    const targetContact = contacts.value.find(c => c.id === route.query.contactId)
    if (targetContact) {
      selectContact(targetContact)
    }
  }
  startPolling() // 组件挂载时开始轮询
})

onUnmounted(() => {
  stopPolling() // 组件卸载时停止轮询
})
</script>

<style scoped>
.message-container {
  display: flex;
  height: 100vh;
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
}

.contacts {
  width: 30%;
  border-right: 1px solid #ccc;
  padding: 1rem;
  overflow-y: auto;
  background-color: #fff;
}

.contacts h3 {
  margin-top: 1rem;
  margin-bottom: 0.5rem;
  font-size: 1rem;
  color: #555;
}

.contacts ul {
  list-style: none;
  padding: 0;
}

.contacts li {
  padding: 0.5rem 1rem;
  margin-bottom: 0.3rem;
  cursor: pointer;
  border-radius: 6px;
  transition: background-color 0.2s ease;
}

.contacts li:hover {
  background-color: #f0f0f0;
}

.contacts li.active {
  background-color: #007bff;
  color: white;
}

.chat-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f7f7f7;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
}

.message {
  max-width: 70%;
  word-wrap: break-word;
  padding: 0.5rem 1rem;
  border-radius: 10px;
  background-color: #e5e5ea;
  margin-bottom: 1rem;
  align-self: flex-start;
}

.message.mine {
  align-self: flex-end;
  background-color: #dcf8c6;
}

.input-area {
  display: flex;
  padding: 1rem;
  border-top: 1px solid #ccc;
  background-color: #fff;
}

.message-input {
  flex: 1;
  padding: 0.5rem;
  resize: none;
  height: 60px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 0.5rem 1rem;
  margin-left: 0.5rem;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.chat-header {
  padding: 1rem;
  background-color: #ffffff;
  border-bottom: 1px solid #ddd;
  font-weight: bold;
  color: #333;
}
</style>